import 'package:flutter/material.dart';

class ContextRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Context测试'),
      ),
      body: Container(
        child: Builder(
          builder: (context) {
            Scaffold scaffold = context.findAncestorWidgetOfExactType<Scaffold>()!;
            return (scaffold.appBar as AppBar).title!;
          },
        ),
      ),
    );
  }
}

class CounterWidget extends StatefulWidget {
  const CounterWidget({
    Key? key,
    this.initValue: 0,
  });

  final int initValue;

  @override
  State<StatefulWidget> createState() {
    return _CounterWidgetState();
  }
}

class _CounterWidgetState extends State<CounterWidget> {
  late int _counter;

  @override
  void initState() {
    super.initState();
    _counter = widget.initValue;
    print('initState');
  }

  @override
  Widget build(BuildContext context) {
    print('build');
    return Scaffold(
      body: Center(
        child: FlatButton(
          child: Text('$_counter'),
          onPressed: () => setState(() => ++_counter),
        ),
      ),
    );
  }

  @override
  void didUpdateWidget(covariant CounterWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    print('didUpdateWidget');
  }

  @override
  void deactivate() {
    super.deactivate();
    print('deactivate');
  }

  @override
  void dispose() {
    super.dispose();
    print('dispose');
  }

  @override
  void reassemble() {
    super.reassemble();
    print('reassemble');
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print('didChangeDependencies');
  }
}

class StateFromContext extends StatelessWidget {
  static GlobalKey<ScaffoldState> _globalKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _globalKey,
      appBar: AppBar(
        title: Text('子树中获取State对象'),
      ),
      body: Center(
        child: Builder(
          builder: (context) {
            return RaisedButton(
              onPressed: () {
                // ScaffoldState? _state = context.findAncestorStateOfType<ScaffoldState>();
                // ScaffoldState _state = Scaffold.of(context);
                ScaffoldState? _state = _globalKey.currentState;

                ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('我是SnackBar')));
                // _state?.showSnackBar(SnackBar(content: Text('我是SnackBar')));
              },
              child: Text('显示SnackBar'),
            );
          },
        ),
      ),
    );
  }
}
